package com.jd.risk.bankorder.service.privilege;

import com.jd.risk.bankorder.common.CommonResult;
import com.jd.risk.bankorder.dao.privilege.RoleMapper;
import com.jd.risk.bankorder.entity.privilege.Role;
import com.jd.risk.bankorder.entity.privilege.RoleExample;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class RoleService {

	
	@Autowired
	private RoleMapper roleMapper;
	
	public CommonResult<Role> getAllRole() {
		
		CommonResult<Role> res = new CommonResult<Role>();
		RoleExample roleExample = new RoleExample();
		List<Role> roles = roleMapper.selectByExample(roleExample);
		Long count = roleMapper.countByExample(roleExample);
		res.setSuccess(true);
		res.setRows(roles);
		res.setTotal(count);
		
		return res;
	}

	public int authorizate(Long roleId, String resourceIds) {
		
		Role role = new Role();
		role.setId(roleId);
		role.setResourceIds(resourceIds);
		int rest = roleMapper.updateByPrimaryKeySelective(role);
		return rest;
	}

	public Role getRoleByRoleId(Long roleId )
	{
		return roleMapper.selectByPrimaryKey(roleId);
	}

	public List<Role> getAllRoleList() {
		
		
		return roleMapper.selectByExample(null);
	}

	public int roleAdd(Role role) {
		
		return roleMapper.insertSelective(role);
	}

	public Set<Role> getRoleByRoleIds(String roleIds) {
		Set<Role> roleset = new HashSet<Role>();
		if(StringUtils.isNotBlank(roleIds) && roleIds.contains(","))
		{
			String[] idseg = roleIds.split(",");
			for(String id :idseg)
			{
				if(StringUtils.isNotBlank(id))
				{
					id = id.trim();
					Role role = getRoleByRoleId(Long.parseLong(id));
					roleset.add(role);
				}
			}
		}
		return roleset;
	}
	
	public Set<String> getRoleStrByRoleIds(String roleIds)
	{
		Set<String> roleset = new HashSet<String>();
		Set<Role> roles = getRoleByRoleIds(roleIds);
		for(Role role :roles)
		{
			roleset.add(role.getRole());
		}
		
		return roleset;
	}
}
